extends Node2D
class_name Main


const BRIDGE_SIZE :Vector2= Vector2(60,60)

@onready var camera_2d: Camera2D = $Camera2D
@onready var divider_line: DividerLine = $SubLayer/DividerLine
@onready var sub_layer: CanvasLayer = $SubLayer
@onready var sub_viewport: SubViewport = $SubLayer/SubViewportContainer/SubViewport
@onready var camera_2d_2: Camera2D = $SubLayer/SubViewportContainer/SubViewport/Camera2D
@onready var subviewport_texture: TextureRect = $SubLayer/TextureRect
@onready var fack_bridge: TextureRect = $FackBridge
@onready var transition_parent: Control = %TransitionParent
@onready var kill_zone: Area2D = $KillZone
@onready var ui: UI = $UI

var current_npc:Npc:
	set(v):
		if current_npc != v:
			current_npc = v
			divider_line.current_npc = v
			current_npc.npc_emotion_changed.connect(on_npc_emotion_changed)
var start_build:bool
var input_index:int = -1
var is_emit:bool
var is_seven:bool
var is_show_setting:bool
var cam_pos:Vector2
var mouse_cell_pos:Vector2
var start_positon:Vector2

func _ready() -> void:
	Global.main = self
	start_positon = Global.player.global_position
	GameEvents.player_in_build.connect(func(): 
		start_build = true
		fack_bridge.visible = true
		start_positon = Global.player.global_position
		)
	GameEvents.player_out_build.connect(func(): 
		start_build = false
		fack_bridge.visible = false
		)
	GameEvents.stage_entered.connect(func():
		camera_2d.top_level = false
		is_emit = false
	)
	kill_zone.body_entered.connect(func(body:Node2D): body.die())
	sub_viewport.world_2d = get_viewport().world_2d


func _process(delta: float) -> void:
	if camera_2d.top_level:
		camera_2d.global_position.y = Global.player.global_position.y
	if camera_2d_2.global_position.x - Global.player.global_position.x < 640 && !is_emit:
		is_emit = true
		current_npc.npc_in_screen.emit()
		subviewport_texture.visible = false
	if start_build:
		mouse_cell_pos = Vector2i(get_global_mouse_position()/BRIDGE_SIZE)
		if mouse_cell_pos.x <= 0:
			mouse_cell_pos.x -= 1 
		if mouse_cell_pos.y < 0:
			mouse_cell_pos.y -= 1
		var base_pos = mouse_cell_pos*BRIDGE_SIZE.x
		fack_bridge.global_position = base_pos
		fack_bridge.texture = ui.get_select_bridge().get_texture()
		if current_npc.current_emotion == Npc.Emotion.DEPRESSED:
			fack_bridge.modulate = Color(0.264, 1.626, 1.626)
		else:
			fack_bridge.modulate = Color.WHITE
		
		# 计算鼠标在格子内的相对位置，决定旋转角度
		var cell_center = base_pos + BRIDGE_SIZE / 2.0
		var diff = get_global_mouse_position() - cell_center
		var angle = 0.0
		if abs(diff.x) > abs(diff.y):
			# 横向主导
			if diff.x < 0: # 左
				angle = 90.0
			else: # 右
				angle = 270.0
		else:
			# 纵向主导
			if diff.y < 0: # 上
				angle = 180.0
			else: # 下
				angle = 0.0
		
		fack_bridge.pivot_offset = Vector2.ZERO
		fack_bridge.rotation_degrees = angle
		
		var offset = Vector2.ZERO
		if angle == 90.0:
			offset = Vector2(BRIDGE_SIZE.x, 0)
		elif angle == 180.0:
			offset = BRIDGE_SIZE
		elif angle == 270.0:
			offset = Vector2(0, BRIDGE_SIZE.y)
		fack_bridge.global_position = base_pos + offset
		

func _input(event: InputEvent) -> void:
	if start_build:
		if event.is_action_pressed("build"):
			if Global.player.current_energy > 0:
				# 在放置前处理 MANIA 规则：仅当四邻域存在 collision_layer==1 的物体时允许放置
				var allow_place: bool = true
				if current_npc != null and current_npc.current_emotion == Npc.Emotion.MANIA:
					allow_place = false
					var offsets := [Vector2(0,-1), Vector2(0,1), Vector2(-1,0), Vector2(1,0)]
					var space = get_world_2d().direct_space_state
					for o in offsets:
						var cell = Vector2(mouse_cell_pos.x + int(o.x), mouse_cell_pos.y + int(o.y)) * BRIDGE_SIZE + BRIDGE_SIZE/2
						# 在该点检测 collision_layer == 1 的碰撞体
						# 使用一个小的查询形状检测指定点上的碰撞（兼容不同 Godot 版本）
						var params = PhysicsShapeQueryParameters2D.new()
						var circle = CircleShape2D.new()
						circle.radius = 6.0
						params.shape = circle
						params.transform = Transform2D(0, cell)
						# 只检测 layer 1
						params.collision_mask = 1
						# 同时检测 Area 和 Body，不区分类型
						params.collide_with_bodies = true
						params.collide_with_areas = true
						var res = space.intersect_shape(params, 1)
						if res.size() > 0:
							allow_place = true
							break
				var space = get_world_2d().direct_space_state
				var cell_center = mouse_cell_pos * BRIDGE_SIZE + BRIDGE_SIZE / 2.0
				var params = PhysicsShapeQueryParameters2D.new()
				var circle = CircleShape2D.new()
				circle.radius = 6.0
				params.shape = circle
				params.transform = Transform2D(0, cell_center)
				# 只检测 layer 1
				params.collision_mask = 1
				# 同时检测 Area 和 Body，不区分类型
				params.collide_with_bodies = true
				params.collide_with_areas = true
				var res = space.intersect_shape(params, 1)
				if res.size() > 0:
					allow_place = false
				
				
				if not allow_place:
					# 触发假桥震动提示（短促左右抖动），并阻止放置
					set_process(false)
					var orig_x = fack_bridge.global_position.x
					var tw = create_tween()
					tw.set_ignore_time_scale()
					tw.tween_property(fack_bridge, "global_position:x", orig_x + 10, 0.06).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_OUT)
					tw.tween_property(fack_bridge, "global_position:x", orig_x - 8, 0.06).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
					tw.tween_property(fack_bridge, "global_position:x", orig_x, 0.06).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN)
					tw.tween_callback(set_process.bind(true))
					return
				
				Global.player.current_energy -= 1
				var bridge = ui.get_select_bridge().duplicate(DUPLICATE_SCRIPTS)
				bridge.global_position = fack_bridge.global_position + BRIDGE_SIZE/2
				var offset = Vector2.ZERO
				if fack_bridge.rotation_degrees == 90.0:
					offset = Vector2(BRIDGE_SIZE.x, 0)
				elif fack_bridge.rotation_degrees == 180.0:
					offset = BRIDGE_SIZE
				elif fack_bridge.rotation_degrees == 270.0:
					offset = Vector2(0, BRIDGE_SIZE.y)
				bridge.global_position -= offset
				bridge.rotation_degrees = fack_bridge.rotation_degrees
				MusicPlayer.play_sfx("BuildBridge")
				add_child(bridge)
				

func divider_half() -> void:
	divider_line.change_position()
	var tween := create_tween()
	tween.tween_property(camera_2d,"offset:x", 320,0.3).set_ease(Tween.EASE_IN_OUT).set_trans(Tween.TRANS_CUBIC)
	is_seven = false

func divider_seven() -> void:
	divider_line.change_position(0.3,DividerLine.Type.SEVEN)
	var tween := create_tween()
	tween.tween_property(camera_2d,"offset:x", 197,0.3).set_ease(Tween.EASE_IN_OUT).set_trans(Tween.TRANS_CUBIC)
	is_seven = true

func _on_divider_line_hidden() -> void:
	cam_pos = camera_2d.global_position
	camera_2d.top_level = true
	camera_2d.global_position = cam_pos
	if Global.current_stage_name == "stage1":
		current_npc.action()

func on_npc_emotion_changed(emo: Npc.Emotion) -> void:
	ui.change_with_emotion(emo)
